<?php

/**
 * CCoreBaseUtils
 *
 * @author Usenko Timur <usenko.timur@gmail.com>
 * @package base
 */

/**
 * @package base
 */
class CCoreBaseUtils
{
	#<editor-fold defaultstate="collapsed" desc="construct (private)">
	private function __construct() {}
	#</editor-fold>
	
	/**
	 * @param string $sText
	 * @return string
	 */
	public static function ShowCRLF($sText)
	{
		CCore::CheckTypes(array('$sText'));
		
		return str_replace(array("\r", "\n"), array('\r', '\n'), $sText);
	}
	
	/**
	 * @param string $sAttributeValue
	 * @return string
	 */
	public static function HtmlAttributeQuote($sAttributeValue)
	{
		CCore::CheckTypes(array('$sAttributeValue'));

		return str_replace('\'', '&#039;', str_replace('"', '&quot;', $sAttributeValue));
	}

	/**
	 * @param string $sAttributeValue
	 * @return string
	 */
	public static function InlineRebuildStringToJsString($sText)
	{
		static $aJsonReplaces = array(
			array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'),
			array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"'));

		return str_replace($aJsonReplaces[0], $aJsonReplaces[1], $sText);
	}

	/**
	 * @param mixed $mInput
	 * @return string
	 */
	public static function Php2js($mInput = false)
	{
		if (is_null($mInput))
		{
			return 'null';
		}
		else if ($mInput === false)
		{
			return 'false';
		}
		else if ($mInput === true)
		{
			return 'true';
		}
		else if (is_scalar($mInput))
		{
			if (is_float($mInput))
			{
				$mInput = str_replace(',', '.', strval($mInput));
			}

			return '"'.self::InlineRebuildStringToJsString($mInput).'"';
		}

		$bIsList = true;
		for ($i = 0, reset($mInput), $c = count($mInput); $i < $c; $i++, next($mInput))
		{
			if (key($mInput) !== $i)
			{
				$bIsList = false;
				break;
			}
		}

		$aResult = array();
		if ($bIsList)
		{
			foreach ($mInput as $mValue)
			{
				$aResult[] = self::Php2js($mValue);
			}
			return '[ ' . join(', ', $aResult) . ' ]';
		}
		else
		{
			foreach ($mInput as $sKey => $mValue)
			{
				$aResult[] = self::Php2js($sKey) . ': ' . self::Php2js($mValue);
			}
			return '{ ' . join(', ', $aResult) . ' }';
		}
	}

	/**
	 * @param string $sEmail
	 * @return string
	 */
	public static function GetAccountNameFromEmail($sEmail)
	{
		CCore::CheckTypes(array('$sEmail'));

		if (!empty($sEmail))
		{
			$iPos = strpos($sEmail, '@');
			return (false === $iPos) ? $sEmail : substr($sEmail, 0, $iPos);
		}

		return '';
	}

	/**
	 * @param string $sEmail
	 * @return string
	 */
	public static function GetDomainFromEmail($sEmail)
	{
		CCore::CheckTypes(array('$sEmail'));

		if (!empty($sEmail))
		{
			$iPos = strpos($sEmail, '@');
			if (false !== $iPos)
			{
				return substr($sEmail, $iPos + 1);
			}
		}
		return '';
	}

	/**
	 * @return string
	 */
	public static function GetTimeWithMicroSec()
	{
		$aMicroTimeItems = explode(' ', microtime());
		return date('H:i:s', $aMicroTimeItems[1]).'.'.str_pad((int) ($aMicroTimeItems[0] * 1000), 3, '0', STR_PAD_LEFT);
	}

	/**
	 * @param string $sFileName
	 * @return string
	 */
	public static function ClearFileName($sFileName)
	{
		return str_replace(array('"', '/', '\\', '*', '?', '<', '>', '|', ':', "\r", "\n", "\t"), ' ', $sFileName);
	}

	/**
	 * @param string $sString
	 * @param string $sFromEncoding
	 * @param string $sToEncoding
	 * @return string
	 */
	public static function ConvertEncoding($sString, $sFromEncoding, $sToEncoding)
	{
		CCore::CheckTypes(array('$sString', '$sFromEncoding', '$sToEncoding'));

		if (0 === strlen(trim($sString)) || strtolower($sFromEncoding) === strtolower($sToEncoding))
		{
			return $sString;
		}

		if ((strtolower($sFromEncoding) === 'iso-8859-1' || strtolower($sFromEncoding) === 'ansi')
			&& strtolower($sToEncoding) === 'utf-8' && function_exists('utf8_encode'))
		{
			return utf8_encode($sString);
		}

		if ((strtolower($sToEncoding) === 'iso-8859-1' || strtolower($sToEncoding) === 'ansi')
			&& strtolower($sFromEncoding) === 'utf-8' && function_exists('utf8_decode'))
		{
			return utf8_decode($sString);
		}

		return self::IconvEncoding($sString, $sFromEncoding, $sToEncoding);
	}

	/**
	 * @param string $sString
	 * @param string $sFromEncoding
	 * @param string $sToEncoding
	 * @return string
	 */
	public static function IconvEncoding($sString, $sFromEncoding, $sToEncoding)
	{
		if ('ks_c_5601-1987' === strtolower($sFromEncoding))
		{
			$sFromEncoding = 'EUC-KR';
		}

		static $aIconvEncodingsArray = array('ascii',
			'iso-8859-1','iso-8859-2','iso-8859-3','iso-8859-4','iso-8859-5','iso-8859-6','iso-8859-7',
			'iso-8859-8','iso-8859-9','iso-8859-10','iso-8859-11','iso-8859-12','iso-8859-13','iso-8859-14',
			'iso-8859-15','iso-8859-16',
			'koi8-r', 'koi8-u', 'koi8-ru',
			'cp1250', 'cp1251', 'cp1252', 'cp1253', 'cp1254', 'cp1257', 'cp949', 'cp1133',
			'cp850', 'cp866', 'cp1255', 'cp1256', 'cp862', 'cp874', 'cp932', 'cp950', 'cp1258',
			'windows-1250', 'windows-1251','windows-1252','windows-1253','windows-1254','windows-1255',
			'windows-1256', 'windows-1257', 'windows-1258', 'windows-874',
			'macroman', 'maccentraleurope', 'maciceland', 'maccroatian', 'macromania', 'maccyrillic',
			'macukraine', 'macgreek', 'macturkish', 'macintosh', 'machebrew', 'macarabic',
			'euc-jp', 'shift_jis', 'iso-2022-jp', 'iso-2022-jp-2', 'iso-2022-jp-1',
			'euc-cn', 'gb2312', 'hz', 'gbk', 'gb18030', 'euc-tw', 'big5', 'big5-hkscs',
			'iso-2022-cn', 'iso-2022-cn-ext', 'euc-kr', 'iso-2022-kr', 'johab',
			'armscii-8', 'georgian-academy', 'georgian-ps', 'koi8-t',
			'tis-620', 'macthai', 'mulelao-1',
			'viscii', 'tcvn', 'hp-roman8', 'nextstep',
			'utf-8', 'ucs-2', 'ucs-2be', 'ucs-2le', 'ucs-4', 'ucs-4be', 'ucs-4le',
			'utf-16', 'utf-16be', 'utf-16le', 'utf-32', 'utf-32be', 'utf-32le', 'utf-7',
			'c99', 'java', 'ucs-2-internal', 'ucs-4-internal');

		if (in_array(strtolower($sFromEncoding), $aIconvEncodingsArray))
		{
			$sResult = @iconv($sFromEncoding, $sToEncoding.'//IGNORE', $sString);
			return (false !== $sResult) ? $sResult : $sString;
		}

		return $sString;
	}

	/**
	 * @param string $str
	 * @return string
	 */
	function Utf7ModifiedToUtf8($str)
	{
		$array = array(-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62, 63,-1,-1,-1,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1);

		$result = '';
		$error = '';
		$strlen = strlen($str);

		for ($i = 0; $strlen > 0; $i++, $strlen--)
		{
			$char = $str{$i};
			if ($char == '&')
			{
				$i++;
				$strlen--;

				$char = isset($str{$i}) ? $str{$i} : null;
				if ($char === null) break;

				if ($strlen && $char == '-')
				{
					$result .= '&';
					continue;
				}

				$ch = 0;
				$k = 10;
				for (; $strlen > 0; $i++, $strlen--)
				{
					$char = $str{$i};

					$b = $array[ord($char)];
					if ((ord($char) & 0x80) || $b == -1) break;

					if ($k > 0)
					{
						$ch |= $b << $k;
						$k -= 6;
					}
					else
					{
						$ch |= $b >> (-$k);
						if ($ch < 0x80)
						{
							if (0x20 <= $ch && $ch < 0x7f)
							return $error;
							$result .= chr($ch);
						}
						else if ($ch < 0x800)
						{
							$result .= chr(0xc0 | ($ch >> 6));
							$result .= chr(0x80 | ($ch & 0x3f));
						}
						else
						{
							$result .= chr(0xe0 | ($ch >> 12));
							$result .= chr(0x80 | (($ch >> 6) & 0x3f));
							$result .= chr(0x80 | ($ch & 0x3f));
						}

						$ch = ($b << (16 + $k)) & 0xffff;
						$k += 10;
					}
				}

				if ($ch || $k < 6) return $error;
				if (!$strlen || $char != '-') return $error;
				if ($strlen > 2 && $str{$i+1} == '&' && $str{$i+2} != '-') return $error;
			}
			else if (ord($char) < 0x20 || ord($char) >= 0x7f)
			{
				return $error;
			}
			else
			{
				$result .= $char;
			}
		}

		return $result;
	}

	/**
	 * @param string $str
	 * @return string
	 */
	function Utf8ToUtf7Modified($str)
	{
		$array = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7','8','9','+',',');

		$strlen = strlen($str);
		$isB = false;
		$i = $n = 0;
		$return = '';
		$error = '';

		while ($strlen)
		{
			$c = ord($str{$i});
			if ($c < 0x80)
			{
				$ch = $c;
				$n = 0;
			}
			else if ($c < 0xc2)
			{
				return $error;
			}
			else if ($c < 0xe0)
			{
				$ch = $c & 0x1f;
				$n = 1;
			}
			else if ($c < 0xf0)
			{
				$ch = $c & 0x0f;
				$n = 2;
			}
			else if ($c < 0xf8)
			{
				$ch = $c & 0x07;
				$n = 3;
			}
			else if ($c < 0xfc)
			{
				$ch = $c & 0x03;
				$n = 4;
			}
			else if ($c < 0xfe)
			{
				$ch = $c & 0x01;
				$n = 5;
			}
			else
			{
				return $error;
			}

			$i++;
			$strlen--;

			if ($n > $strlen)
			{
				return $error;
			}

			for ($j=0; $j < $n; $j++)
			{
				$o = ord($str{$i+$j});
				if (($o & 0xc0) != 0x80)
				{
					return $error;
				}
				$ch = ($ch << 6) | ($o & 0x3f);
			}

			if ($n > 1 && !($ch >> ($n * 5 + 1)))
			{
				return $error;
			}

			$i += $n;
			$strlen -= $n;

			if ($ch < 0x20 || $ch >= 0x7f)
			{
				if (!$isB)
				{
					$return .= '&';
					$isB = true;
					$b = 0;
					$k = 10;
				}

				if ($ch & ~0xffff)
				{
					$ch = 0xfffe;
				}

				$return .= $array[($b | $ch >> $k)];
				$k -= 6;
				for (; $k >= 0; $k -= 6)
				{
					$return .= $array[(($ch >> $k) & 0x3f)];
				}

				$b = ($ch << (-$k)) & 0x3f;
				$k += 16;
			}
			else
			{
				if ($isB)
				{
					if ($k > 10)
					{
						$return .= $array[$b];
					}
					$return .= '-';
					$isB = false;
				}

				$return .= chr($ch);
				if (chr($ch) == '&')
				{
					$return .= '-';
				}
			}
		}

		if ($isB)
		{
			if ($k > 10)
			{
				$return .= $array[$b];
			}
			$return .= '-';
		}

		return $return;
	}
}